<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{MemberPackage, UserPackage};
use think\facade\{Db, Log};
use think\Request;

class PackageController extends BaseController
{
    /**
     * 获取套餐列表
     */
    public function list(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $list = MemberPackage::where('merchant_id', $merchant_id)
                ->withCount(['users'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取套餐列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 创建套餐
     */
    public function create(Request $request)
    {
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            $validate = validate('MemberPackage');
            if (!$validate->check($params)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            
            MemberPackage::create([
                'merchant_id' => $merchant_id,
                'package_name' => $params['package_name'],
                'package_price' => $params['package_price'],
                'package_desc' => $params['package_desc'],
                'discount_rate' => $params['discount_rate'],
                'valid_time' => $params['valid_time']
            ]);
            
            return json(['code' => 0, 'msg' => '创建成功']);
        } catch (\Exception $e) {
            Log::error('创建套餐失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 更新套餐
     */
    public function update(Request $request)
    {
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            $validate = validate('MemberPackage');
            if (!$validate->check($params)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            
            $package = MemberPackage::where([
                'id' => $params['id'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$package) {
                return json(['code' => 1, 'msg' => '套餐不存在']);
            }
            
            $package->save([
                'package_name' => $params['package_name'],
                'package_price' => $params['package_price'],
                'package_desc' => $params['package_desc'],
                'discount_rate' => $params['discount_rate'],
                'valid_time' => $params['valid_time'],
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            return json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Log::error('更新套餐失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 删除套餐
     */
    public function delete(Request $request)
    {
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            $package = MemberPackage::where([
                'id' => $params['id'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$package) {
                return json(['code' => 1, 'msg' => '套餐不存在']);
            }
            
            // 检查是否有用户正在使用该套餐
            $using = UserPackage::where([
                'package_id' => $params['id'],
                'status' => 1 // 生效中
            ])->count();
            
            if ($using > 0) {
                return json(['code' => 1, 'msg' => '该套餐正在使用中,不能删除']);
            }
            
            $package->delete();
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Log::error('删除套餐失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取套餐购买记录
     */
    public function records(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 套餐ID筛选
            if (!empty($params['package_id'])) {
                $where[] = ['package_id', '=', $params['package_id']];
            }
            
            // 用户筛选
            if (!empty($params['keyword'])) {
                $where[] = ['user_id', 'in', function ($query) use ($params) {
                    $query->name('user')
                        ->where('mobile|real_name', 'like', "%{$params['keyword']}%")
                        ->field('id');
                }];
            }
            
            $list = UserPackage::where($where)
                ->with(['user', 'package'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取套餐购买记录失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 